<template>
  <div class="purchase-order-add-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>新增调拨订单</h2>
      <div class="header-actions">
        <el-button @click="handleCancel">
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
      </div>
    </div>

    <!-- 基础信息区域 -->
    <el-card class="form-card">
      <template #header>
        <div class="card-header">
          <span>基础信息</span>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        class="purchase-form"
      >
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="调拨类型" prop="transferType">
              <el-select v-model="formData.transferType" placeholder="请选择">
                <el-option label="库存调拨" value="库存调拨" />
                <el-option label="库存预警" value="库存预警" />
                <el-option label="满仓调离" value="满仓调离" />
                <el-option label="其他调拨" value="其他调拨" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="经办人" prop="handler">
              <el-select
                v-model="formData.handler"
                placeholder="请选择经办人"
                style="width: 100%"
              >
                <el-option
                  v-for="user in userList"
                  :key="user.user_Id"
                  :label="user.userTrueName || user.userName"
                  :value="user.userTrueName || user.userName"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="10">
            <el-form-item label="调拨申请日期" prop="applyDate">
              <el-date-picker 
                v-model="formData.applyDate" 
                type="date" 
                placeholder="请选择"
              />
            </el-form-item> 
          </el-col>

          <el-col :span="10">
            <el-form-item label="创建人" prop="creator">
              <el-input
                v-model="formData.creator"
                placeholder="请输入创建人"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="10">
             <el-form-item label="调出仓库" prop="outWarehouseId">
              <el-select
                v-model="formData.outWarehouseId"
                placeholder="请选择调出仓库"
                style="width: 100%"
              >
                <el-option
                  v-for="warehouse in warehouseList"
                  :key="warehouse.id"
                  :label="warehouse.warehouseName"
                  :value="warehouse.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
             <el-form-item label="调入仓库" prop="inWarehouseId">
              <el-select
                v-model="formData.inWarehouseId"
                placeholder="请选择调入仓库"
                style="width: 100%"
              >
                <el-option
                  v-for="warehouse in warehouseList"
                  :key="warehouse.id"
                  :label="warehouse.warehouseName"
                  :value="warehouse.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                v-model="formData.remarks"
                type="textarea"
                :rows="3"
                placeholder="请输入备注信息"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 进货明细区域 -->
    <el-card class="form-card">
      <template #header>
        <div class="card-header">
          <span>调拨明细</span>
          <el-button type="primary" @click="openProductDialog">
            <el-icon><Plus /></el-icon>
            添加货品
          </el-button>
        </div>
      </template>

      <!-- 明细列表 -->
      <el-table :data="formData.orderItems" border style="width: 100%">
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column label="货品编号" prop="goodsCode" width="120" />
        <el-table-column label="货品名称" prop="goodsName" width="150" />
        <el-table-column label="规格型号" prop="specification" width="120" />
        <el-table-column label="进货单价" width="120">
          <template #default="{ row, $index }">
            <el-input
              v-model="row.unitPrice"
              placeholder="请输入单价"
              type="number"
              style="width: 100%"
              @input="calculateItemAmount($index)"
            />
          </template>
        </el-table-column>
        <el-table-column label="当前库存" prop="currentInventory" width="100" />
        <el-table-column label="单位" width="100">
          <template #default="{ row, $index }">
            <el-select
              v-model="row.unitName"
              placeholder="请选择"
              style="width: 100%"
              @change="calculateItemAmount($index)"
            >
              <el-option
                v-for="unit in unitList"
                :key="unit.id"
                :label="unit.unitName"
                :value="unit.unitName"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="货品数量" width="120">
          <template #default="{ row, $index }">
            <el-input
              v-model="row.quantity"
              placeholder="请输入数量"
              type="number"
              style="width: 100%"
              @input="calculateItemAmount($index)"
            />
          </template>
        </el-table-column>
        <el-table-column label="金额" width="120">
          <template #default="{ row }">
            ¥{{ row.amount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="备注" width="150">
          <template #default="{ row }">
            <el-input
              v-model="row.remark"
              placeholder="请输入备注"
              size="small"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <template #default="{ $index }">
            <el-button
              type="danger"
              size="small"
              @click="removeItem($index)"
            >
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 合计信息 -->
      <div class="total-summary">
        <el-row justify="center">
          <el-col :span="24">
            <div class="summary-display">
              <span class="summary-item">货品种类: {{ formData.orderItems.length }}</span>
              <span class="summary-item">货品数量: {{ totalQuantity }}</span>
              <span class="summary-item">总金额: ¥{{ totalAmount.toFixed(2) }}</span>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 操作按钮 -->
    <div class="form-actions">
      <el-button type="success" @click="handleSave" :loading="saveLoading">
        <el-icon><Check /></el-icon>
        保存订单
      </el-button>
      <el-button @click="handleReset">
        <el-icon><Refresh /></el-icon>
        重置
      </el-button>
      <el-button @click="handleCancel">
        <el-icon><Close /></el-icon>
        取消
      </el-button>
    </div>
  </div>

  <!-- 货品选择对话框 -->
  <el-dialog
    v-model="productDialogVisible"
    title="选择货品"
    width="80%"
    :close-on-click-modal="false"
  >
    <div class="product-dialog">
      <!-- 搜索区域 -->
      <div class="search-section">
        <el-input
          v-model="productSearchKeyword"
          placeholder="搜索货品名称或编码"
          @input="searchProducts"
          style="width: 300px"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>

      <!-- 货品列表 -->
      <el-table
        :data="productList"
        border
        style="width: 100%"
        @selection-change="handleProductSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="goodsCode" label="货品编号" width="120" />
        <el-table-column prop="goodsName" label="货品名称" width="200" />
        <el-table-column prop="specModel" label="规格型号" width="150" />
        <el-table-column prop="purchasePrice" label="入库单价" width="100">
          <template #default="{ row }">
            ¥{{ row.purchasePrice }}
          </template>
        </el-table-column>
        <el-table-column prop="currentInventory" label="当前库存" width="100" />
        <el-table-column prop="typeName" label="货品类型" width="150" />
        <el-table-column prop="unitName" label="单位" width="150" />
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="productPagination.pageIndex"
          v-model:page-size="productPagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="productPagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadProducts"
          @current-change="loadProducts"
        />
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="productDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmProductSelection">
          确定选择
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, computed, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  ArrowLeft, 
  Plus, 
  Check, 
  Close, 
  Refresh, 
  Search 
} from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

// 获取实例
const { proxy } = getCurrentInstance()
const router = useRouter()

// 响应式数据
const formRef = ref()
const saveLoading = ref(false)
const productDialogVisible = ref(false)
const productSearchKeyword = ref('')

// 基础数据列表
const supplierList = ref([])
const userList = ref([])
const deptList = ref([])
const unitList = ref([
  { id: 'DWBH1487', unitName: '部' },
  { id: 'DWBH8938', unitName: '支' },
  { id: 'DWBH7420', unitName: '包' },
  { id: 'DWBH795', unitName: '条' },
  { id: 'DWBH7087', unitName: '台' },
  { id: 'DWBH4611', unitName: '个' },
  { id: 'DWBH5456', unitName: '套' },
  { id: 'DWBH1234', unitName: '瓶' },
  { id: 'DWBH5678', unitName: '粒' },
  { id: 'DWBH9012', unitName: '克' },
  { id: 'DWBH3456', unitName: '卡' },
  { id: 'DWBH7890', unitName: '卷' },
  { id: 'DWBH2345', unitName: '斤' },
  { id: 'DWBH6789', unitName: '件' },
  { id: 'DWBH0123', unitName: '盒' }
])
const productList = ref([])

// 货品分页
const productPagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0
})

// 选中的货品
const selectedProducts = ref([])

// 仓库列表
const warehouseList = ref([])

// 表单数据
const formData = reactive({
  transferOrderNo: '',
  creator: '',
  department: '',
  transferType: '',
  applyDate: '',
  outWarehouseId: '',
  inWarehouseId: '',
  handler: '',
  remark: '',
  orderStatus: '待审核',
  orderItems: []
})

// 表单验证规则
const formRules = {
  transferType: [{ required: true, message: '请选择调拨类型', trigger: 'change' }],
  handler: [{ required: true, message: '请选择经办人', trigger: 'change' }],
  applyDate: [{ required: true, message: '请选择调拨申请日期', trigger: 'change' }],
  creator: [{ required: true, message: '请输入创建人', trigger: 'blur' }],
  outWarehouseId: [{ required: true, message: '请选择调出仓库', trigger: 'change' }],
  inWarehouseId: [{ required: true, message: '请选择调入仓库', trigger: 'change' }]
}

// 计算总金额
const totalAmount = computed(() => {
  return formData.orderItems.reduce((sum, item) => sum + item.amount, 0)
})

// 计算总数量
const totalQuantity = computed(() => {
  return formData.orderItems.reduce((sum, item) => sum + (parseFloat(item.quantity) || 0), 0)
})

// 处理供应商变化
const handleSupplierChange = async (supplierId) => {
  console.log('=== 供应商变化处理开始 ===')
  console.log('选择的供应商ID:', supplierId)
  
  if (!supplierId) {
    // 清空联系人和联系方式
    formData.contact = ''
    formData.contactPhone = ''
    formData.supplierName = ''
    console.log('供应商ID为空，清空相关字段')
    return
  }

  try {
    console.log('正在获取供应商信息...', supplierId)
    
    // 根据供应商ID查找对应的供应商
    const supplier = supplierList.value.find(s => s.id === supplierId)
    
    console.log('找到的供应商:', supplier)
    
    if (supplier) {
      // 自动填充供应商相关信息
      formData.supplierName = supplier.supplierName || ''
      formData.contact = supplier.supplierContact || ''
      formData.contactPhone = supplier.supplierTel || ''
      
      console.log('自动填充供应商信息:', {
        supplierName: formData.supplierName,
        contact: formData.contact,
        contactPhone: formData.contactPhone
      })
      
      ElMessage.success(`已选择供应商：${supplier.supplierName}`)
    } else {
      console.log('未找到对应的供应商')
      formData.supplierName = ''
      formData.contact = ''
      formData.contactPhone = ''
    }
  } catch (error) {
    console.error('获取供应商信息失败:', error)
    ElMessage.error('获取供应商信息失败')
  }
  
  console.log('=== 供应商变化处理结束 ===')
}
 
const handleWarehouseModel =()=>{ 
    router.push('/WarehouseModel') 
}

// 获取供应商列表
const fetchSupplierList = async () => {
  try {
    console.log('正在获取供应商列表...')
    const response = await proxy.http.get('/api/InboundManagement/GetSupplierOptions', {}, false)
    console.log('供应商列表API响应:', response)
    
    if (response && response.success) {
      supplierList.value = response.data || []
      console.log('供应商列表数据:', supplierList.value)
      console.log('供应商列表示例:', supplierList.value[0])
      
      // 详细打印每个供应商的字段
      if (supplierList.value.length > 0) {
        console.log('供应商字段分析:')
        const firstSupplier = supplierList.value[0]
        console.log('第一个供应商的所有字段:', Object.keys(firstSupplier))
        console.log('第一个供应商的完整数据:', firstSupplier)
      }
    } else {
      console.error('供应商列表API响应错误:', response)
      ElMessage.error(response?.message || '获取供应商列表失败')
      supplierList.value = []
    }
  } catch (error) {
    console.error('获取供应商列表失败:', error)
    ElMessage.error('获取供应商列表失败，请检查网络连接')
    supplierList.value = []
  }
}

// 获取用户列表
const fetchUserList = async () => {
  try {
    console.log('正在获取用户列表...')
    const response = await proxy.http.get('/api/InboundManagement/GetUserOptions', {}, false)
    console.log('用户列表API响应:', response)
    
    if (response && response.success) {
      // 直接使用API返回的数据，不需要转换
      userList.value = response.data || []
      console.log('用户列表数据:', userList.value)
      console.log('用户列表示例:', userList.value[0])
    } else {
      console.error('用户列表API响应错误:', response)
      ElMessage.error(response?.message || '获取用户列表失败')
      userList.value = []
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败，请检查网络连接')
    userList.value = []
  }
}

// 获取仓库列表
const fetchWarehouseList = async () => {
  try {
    console.log('正在获取仓库列表...')
    const response = await proxy.http.post('/api/warehousemodel/GetPageData', {
      pageIndex: 1,
      pageSize: 1000
    }, false)
    console.log('仓库列表API响应:', response)
    
    // 接受status为0的成功响应
    if (response && (response.status === 0 || response.status === true || response.status === 1)) {
      let data = []
      
      // 处理不同的数据格式
      if (response.rows && Array.isArray(response.rows)) {
        data = response.rows
      } else if (response.data?.rows && Array.isArray(response.data.rows)) {
        data = response.data.rows
      } else if (Array.isArray(response.data)) {
        data = response.data
      }
      
      // 转换数据格式，确保字段名兼容
      warehouseList.value = data.map(item => ({
        id: item.Id || item.id || item.warehouseId,
        warehouseName: item.WarehouseName || item.warehouseName || item.name
      })).filter(item => item.id && item.warehouseName)
      
      console.log('仓库列表数据:', warehouseList.value)
      
      // 如果没有获取到仓库数据，使用默认数据
      if (warehouseList.value.length === 0) {
        warehouseList.value = [
          { id: 1, warehouseName: '货品仓库一' },
          { id: 2, warehouseName: '货品仓库二' },
          { id: 3, warehouseName: '货品仓库三' }
        ]
        console.log('使用默认仓库数据')
      }
    } else {
      console.error('仓库列表API响应错误:', response)
      // 不显示错误消息，直接使用默认数据
      warehouseList.value = [
        { id: 1, warehouseName: '货品仓库一' },
        { id: 2, warehouseName: '货品仓库二' },
        { id: 3, warehouseName: '货品仓库三' }
      ]
      console.log('使用默认仓库数据')
    }
  } catch (error) {
    console.error('获取仓库列表失败:', error)
    // 不显示错误消息，直接使用默认数据
    warehouseList.value = [
      { id: 1, warehouseName: '货品仓库一' },
      { id: 2, warehouseName: '货品仓库二' },
      { id: 3, warehouseName: '货品仓库三' }
    ]
    console.log('使用默认仓库数据')
  }
}
 

// 获取货品列表
const loadProducts = async () => {
  try {
    const params = {
      keyword: productSearchKeyword.value,
      pageIndex: productPagination.pageIndex,
      pageSize: productPagination.pageSize
    }
    
    const response = await proxy.http.get('/api/InboundManagement/GetProductOptions', params, false)
    if (response && response.success) {
      productList.value = response.data || []
      productPagination.total = response.total || 0
    }
  } catch (error) {
    console.error('获取货品列表失败:', error)
    ElMessage.error('获取货品列表失败')
  }
}

// 搜索货品
const searchProducts = () => {
  productPagination.pageIndex = 1
  loadProducts()
}


// 打开货品选择对话框
const openProductDialog = () => {
  productDialogVisible.value = true
  productSearchKeyword.value = ''
  selectedProducts.value = []
  loadProducts()
}

// 货品选择变化
const handleProductSelectionChange = (selection) => {
  selectedProducts.value = selection
}

// 确认选择货品
const confirmProductSelection = () => {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning('请选择至少一个货品')
    return
  }

  // 添加选中的货品到明细列表
  selectedProducts.value.forEach(product => {
    // 检查是否已存在
    const exists = formData.orderItems.some(item => item.goodsId === product.id)
    if (!exists) {
      formData.orderItems.push({
        goodsId: product.id,
        goodsName: product.goodsName,
        goodsCode: product.goodsCode,
        specification: product.specModel, // 使用specModel字段
        unitName: '',
        productType: product.productType || '',
        currentInventory: product.currentInventory || 0,
        quantity: 0, // 设置为0而不是空字符串
        unitPrice: product.purchasePrice || 0, // 使用purchasePrice作为默认单价，设置为0而不是空字符串
        amount: 0,
        remark: ''
      })
    }
  })

  productDialogVisible.value = false
  ElMessage.success(`已添加 ${selectedProducts.value.length} 个货品`)
}

// 计算明细项金额
const calculateItemAmount = (index) => {
  const item = formData.orderItems[index]
  if (item) {
    const quantity = parseFloat(item.quantity) || 0
    const unitPrice = parseFloat(item.unitPrice) || 0
    item.amount = quantity * unitPrice
  }
}

// 检查库存是否足够
const checkInventory = async () => {
  for (const item of formData.orderItems) {
    // 这里应该调用API获取实际库存，但目前使用前端模拟
    const currentInventory = parseFloat(item.currentInventory) || 0
    const transferQty = parseFloat(item.quantity) || 0
    const inventoryLowerLimit = currentInventory * 0.2 // 假设下限为当前库存的20%
    
    if (transferQty > currentInventory) {
      ElMessage.error(`${item.goodsName} 库存不足，当前库存：${currentInventory}，调拨数量：${transferQty}，不允许调拨出库！`)
      return false
    }
    
    if (currentInventory - transferQty < inventoryLowerLimit) {
      const confirm = await ElMessageBox.confirm(
        `${item.goodsName} 当前操作库存将低于货品库存下限，是否执行调拨？`,
        '库存预警',
        {
          confirmButtonText: '确定调拨',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(() => false)
      
      if (!confirm) {
        return false
      }
    }
  }
  return true
}

// 删除明细项
const removeItem = (index) => {
  ElMessageBox.confirm('确定要删除这个货品吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    formData.orderItems.splice(index, 1)
    ElMessage.success('删除成功')
  })
}

// 保存调拨单
const handleSave = async () => {
  if (!formRef.value) return

  try {
    // 添加详细的调试日志
    console.log('=== 开始保存调拨单 ===')
    console.log('当前表单数据:', formData)
    console.log('表单验证状态:', formRef.value)
    
    // 1. 基本表单验证
    await formRef.value.validate()
    console.log('表单验证通过')

    // 2. 验证是否选择货品
    if (formData.orderItems.length === 0) {
      ElMessage.warning('请选择货品！')
      return
    }

    // 3. 验证入库/出库仓库是否相同
    if (formData.outWarehouseId === formData.inWarehouseId) {
      ElMessage.error('入库仓库和出库仓库不能为同一仓库！')
      return
    }

    // 4. 验证调拨明细数据
    for (let i = 0; i < formData.orderItems.length; i++) {
      const item = formData.orderItems[i]
      console.log(`检查明细项 ${i + 1}:`, item)
      
      if (!item.goodsId) {
        ElMessage.error(`第${i + 1}个货品的货品ID不能为空`)
        return
      }
      if (!item.quantity || parseFloat(item.quantity) <= 0) {
        ElMessage.error(`货品数量必须大于0！`)
        return
      }
      if (!item.unitPrice || parseFloat(item.unitPrice) <= 0) {
        ElMessage.error(`第${i + 1}个货品的单价必须大于0`)
        return
      }
      if (!item.unitName) {
        ElMessage.error(`第${i + 1}个货品的单位不能为空`)
        return
      }
    }

    // 5. 检查库存是否足够
    const inventoryCheckPass = await checkInventory()
    if (!inventoryCheckPass) {
      return
    }

    saveLoading.value = true

    // 6. 生成调拨单号（实际应该由后端生成）
    const transferOrderNo = 'TRF' + new Date().toISOString().replace(/[-:.TZ]/g, '').slice(0, 14)

    // 7. 准备提交数据 - 按照API要求的格式
    const submitData = {
      transferOrder: {
        transferOrderNo: transferOrderNo,
        creator: formData.creator,
        department: formData.department || '',
        transferType: formData.transferType,
        applyDate: formData.applyDate ? new Date(formData.applyDate).toISOString() : new Date().toISOString(),
        outWarehouseId: parseInt(formData.outWarehouseId),
        inWarehouseId: parseInt(formData.inWarehouseId),
        handler: formData.handler,
        remark: formData.remark || '',
        orderStatus: formData.orderStatus
      },
      details: formData.orderItems.map(item => ({
        transferOrderNo: transferOrderNo,
        productId: parseInt(item.goodsId),
        productName: item.goodsName,
        productNo: item.goodsCode,
        spec: item.specification || '',
        unit: item.unitName,
        productType: item.productType || '',
        transferQty: parseFloat(item.quantity),
        unitPrice: parseFloat(item.unitPrice),
        transferAmount: parseFloat(item.amount)
      }))
    }

    // 8. 打印请求数据
    console.log('=== 调拨单保存请求数据 ===')
    console.log(JSON.stringify(submitData, null, 2))

    // 9. 调用保存API
    const response = await proxy.http.post('/api/transferorder/SaveTransferOrder', submitData, false)

    if (response && response.success) {
      ElMessage.success('调拨单保存成功')
      router.push('/transferorder')
    } else {
      console.error('保存失败，响应:', response)
      ElMessage.error(response?.message || '保存失败，请检查数据格式')
    }
  } catch (error) {
    console.error('保存调拨单失败:', error)
    ElMessage.error('保存调拨单失败，请检查输入信息')
  } finally {
    saveLoading.value = false
  }
}

// 重置表单
const handleReset = () => {
  ElMessageBox.confirm('确定要重置所有数据吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    formRef.value?.resetFields()
    formData.orderItems = []
    formData.contact = ''
    formData.contactPhone = ''
    formData.supplierName = ''
    ElMessage.success('重置成功')
  })
}

// 取消操作
const handleCancel = () => {
  ElMessageBox.confirm('确定要离开吗？未保存的数据将丢失。', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    router.push('/transferorder')
  })
}

// 页面初始化
onMounted(async () => { 
  // 加载基础数据
  try {
    await Promise.all([ 
      fetchUserList(), 
      fetchWarehouseList()
    ])
      
    console.log('页面初始化完成') 
    console.log('用户列表:', userList.value.length)  
    console.log('仓库列表:', warehouseList.value.length)  
  } catch (error) {
    console.error('页面初始化失败:', error)
    ElMessage.error('页面初始化失败，请刷新页面重试')
  }
})


// 备用用户列表获取方案
const fetchUserListFallback = async () => {
  try {
    console.log('尝试备用用户列表获取方案...')
    // 尝试使用系统用户API
    const response = await proxy.http.post('/api/Sys_User/GetPageData', {
      pageIndex: 1,
      pageSize: 1000
    }, false)
    
    console.log('备用用户API响应:', response)
    
    if (response && response.status) {
      const data = response.data?.data || response.data?.rows || []
      userList.value = data.map(user => ({
        user_Id: user.User_Id || user.id,
        userName: user.UserName || user.userName || user.name,
        userTrueName: user.UserTrueName || user.userTrueName || user.trueName
      }))
      console.log('备用用户列表数据:', userList.value)
    }
  } catch (error) {
    console.error('备用用户列表获取失败:', error)
    // 如果备用方案也失败，使用模拟数据
    userList.value = [
      { user_Id: 1, userName: 'admin', userTrueName: '超级管理员' },
      { user_Id: 2, userName: 'admin666', userTrueName: '管理员666' },
      { user_Id: 3, userName: 'cjh', userTrueName: '陈建华' },
      { user_Id: 4, userName: 'laodeng', userTrueName: '老邓' },
      { user_Id: 5, userName: 'liuzong', userTrueName: '刘总' },
      { user_Id: 6, userName: 'tcy', userTrueName: '唐春燕' },
      { user_Id: 7, userName: 'xiaowang', userTrueName: '小王' },
      { user_Id: 8, userName: 'zhangsan', userTrueName: '张三' }
    ]
    console.log('使用模拟用户数据:', userList.value)
  }
}
</script>

<style scoped>
.purchase-order-add-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 10px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.form-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.purchase-form {
  margin-top: 20px;
}

.goods-name {
  font-weight: 500;
  color: #303133;
}

.goods-code {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.total-summary {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
}

.summary-display {
  text-align: center;
  font-size: 16px;
}

.summary-item {
  color: #606266;
  margin: 0 20px;
  font-weight: 500;
}

.summary-item:last-child {
  color: #e6a23c;
  font-weight: bold;
  font-size: 18px;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 30px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.product-dialog {
  max-height: 60vh;
  overflow-y: auto;
}

.search-section {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-table .el-table__row:hover) {
  background-color: #f5f7fa;
}

/* 表单样式 */
:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

/* 按钮样式 */
:deep(.el-button) {
  border-radius: 6px;
}

:deep(.el-button--success) {
  background-color: #67c23a;
  border-color: #67c23a;
}

:deep(.el-button--success:hover) {
  background-color: #85ce61;
  border-color: #85ce61;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .purchase-order-add-container {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
  
  .form-actions {
    flex-direction: column;
  }
}
</style>
